<?php
require_once 'MyPdoCounty.class.php';
class TableShopImg extends MyPdoCounty{
	private $tableName = 'shop_img';

	//删除指定关联商品的所有图片及其商品关联的目录
	public function _goodsImgsDel($goods_id,$dirPath){
		$res = $this->_getImgListForGid($goods_id,'addr');
		//遍历删除upyun上的图片
		if($res){
			$count1 = 0;
			$count2 = count($res);
			for($i=0;$i<count($res);$i++){
				$count1 ++;
				UpyunDelFile($this->config,$res[$i]['addr']);
			}
			if($count1 >= $count2){
				//删除数据库中商品关联的图片数据
				$this->_deleteImgForGid($goods_id);
				//删除商品关联的目录
				UpyunDelDir($this->config,$dirPath);
			}
		}

	}


	//根据goods_id删除商品下所有图片
	public function _deleteImgForGid($goods_id){
		$sql = "delete from {$this->tableName} where gid = ?";
		return $this->dml($sql,array($goods_id));
	}



	//删除单张图片
	public function _goodsImgDel($img_id,$img_addr,$goods_id){
		$has = UpyunHasFile($this->config,$img_addr);
		if($has){	//如果图片存在则删除
			$res = UpyunDelFile($this->config,$img_addr);
		}

		$sql = "delete from {$this->tableName} where id = ? and gid = ?";
		return $this->dml($sql,array($img_id,$goods_id));
	}



	//通过商品id获取图片列表
	public function _getImgListForGid($gid,$fields=false){
		if(!$fields){
			$fields = 'id,addr';
		}
		$sql = "select {$fields} from {$this->tableName} where gid = ?";
		return $this->dql($sql,array($gid));
	}



	//添加商品图片
	function _goodsImgAdd($cityCode,$goods_id,$user){
		$sqlc = "select count(*) as c from {$this->tableName} where gid = ?";
		$resc = $this->dql($sqlc,array($goods_id),1);
		if(@$resc && $resc['c'] >= $this->config['goodsImgMaxCount']){
			return 'err2';	//图片数量超限
		}

		$file = $_FILES['img'];
		$full_path = '/shop_img/'.$cityCode.'/'.$user.'/'.$goods_id.'/'.date('YmdHis').'.jpg';
		$res_upyun = UploadImgToUpyun($this->config,$full_path,$file,$this->config['imgSize']);
		if(is_array($res_upyun)){
			$sql4 = "insert into {$this->tableName}(gid,addr) values(?,?)";
			$res4 = $this->dml($sql4,array($goods_id,$full_path));
			if($res4){
				return 'ok';
			}else{
				UpyunDelFile($config,$full_path);
				return 'err4';  //数据写入失败
			}
		}else if($res_upyun == 'err_img'){
			return 'err5';	//图片大小超限
		}else{
			return 'err3'; //文件上传失败
		}
	}



}